package mywebsocket

import (
	"time"

	"github.com/gorilla/websocket"
)

const (
	checkInterval = 30 * time.Second
	maxIdleTime   = 90 * time.Second
)

type HealthChecker struct {
	manager *Manager
}

func NewHealthChecker(m *Manager) *HealthChecker {
	return &HealthChecker{manager: m}
}

// 启动为后台协程
func (h *HealthChecker) Start() {
	go func() {
		ticker := time.NewTicker(checkInterval)
		defer ticker.Stop()

		for range ticker.C {
			now := time.Now().Unix()
			for _, conn := range h.manager.GetAll() {
				if v, ok := h.manager.Connections.Load(conn); ok {
					c := v.(*Connection)
					if now-c.lastActive > int64(maxIdleTime) {
						conn.Close()
						h.manager.Remove(conn)
						continue
					}

					c.mu.Lock()
					conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(5*time.Second))
					c.mu.Unlock()
				}
			}
		}
	}()
}
